package top.zhangjianyong.utils;


import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/22 10:52 AM
 */
public class UrlUtil {

    /**
     * 获取http协议
     *
     * @param url
     * @return
     */
    public static String protocol(String url) {
        String regex = "(http.?):";
        return RegexUtil.matcherFirst(url, regex, 1);
    }

    /**
     * 获取域名
     *
     * @param url
     * @return
     */
    public static String host(String url) {
        String regex = "http.?://([^/?]*)";
        return RegexUtil.matcherFirst(url, regex, 1);
    }

    public static String top(String url) {
        String regex = "http.?://[a-zA-Z0-9-~\\.]*?(([a-zA-Z0-9-~]{1,}\\.){1}[a-zA-Z0-9-~]{1,}$)";
        return RegexUtil.matcherFirst(url, regex, 1);
    }

    /**
     * 逆转域名
     *
     * @return
     */
    public static String reveres(String host) {
        if (host == null) return "";
        String[] split = host.split("\\.");
        return Arrays.stream(split).sorted((o1, o2) -> -1)
                .collect(Collectors.joining("."));
    }

    public static String reveresHost(String url) {
        String reveres = "";
        try {
            reveres = reveres(getDomainName(url));
        } catch (MalformedURLException e) {
            reveres = reveres(top(url));
        }
        if (isPublicSuffix(reveres)) {
            return "";
        }
        return reveres;
    }

    /**
     * 转主页url
     *
     * @param url
     * @return
     */
    public static String index(String url) {
        try {
            return protocol(url) + "://" + getDomainName(url);
        } catch (MalformedURLException e) {
            return protocol(url) + "://" + top(url);
        }
    }

    public static String prefix(String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, Charset.defaultCharset().name());
        if (url.contains("?")) {
            int i = url.indexOf("?");
            url = url.substring(0, i);
        }

        String regex = "(http.?://.*)/";
        String res = RegexUtil.matcherFirst(url, regex, 1);
        if (res == null) {
            res = url;
        }
        return res;
    }


    public static String getUrl(String location, String url) {
        if (StringUtils.isBlank(location)) {
            location = "";
        }
        if (location.startsWith("http")) {
            return location;
        }
        if (location.startsWith("/")) {
            return protocol(url) + "://" + host(url) + location;
        } else {
            return protocol(url) + "://" + host(url) + "/" + location;
        }
    }

    private final static Set<String> PublicSuffixSet = new HashSet<String>(
            Arrays.asList(new String(
                    "com|org|net|gov|edu|co|tv|mobi|info|asia|xxx|onion|cn|com.cn|edu.cn|gov.cn|net.cn|org.cn|jp|kr|tw|com.hk|hk|com.hk|org.hk|se|com.se|org.se")
                    .split("\\|")));
    private static Pattern IP_PATTERN = Pattern
            .compile("(\\d{1,3}\\.){3}(\\d{1,3})");

    public static boolean isPublicSuffix(String host) {
        return PublicSuffixSet.stream().anyMatch(host::equals);
    }

    /**
     * 获取url的顶级域名
     *
     * @param url
     * @return
     */
    public static String getDomainName(URL url) {
        String host = url.getHost();
        if (host.endsWith("."))
            host = host.substring(0, host.length() - 1);
        if (IP_PATTERN.matcher(host).matches())
            return host;

        int index = 0;
        String candidate = host;
        for (; index >= 0; ) {
            index = candidate.indexOf('.');
            String subCandidate = candidate.substring(index + 1);
            if (PublicSuffixSet.contains(subCandidate)) {
                return candidate;
            }
            candidate = subCandidate;
        }
        return top(url.toString());
    }

    /**
     * 获取url的顶级域名
     *
     * @param url
     * @return
     * @throws MalformedURLException
     */
    public static String getDomainName(String url) throws MalformedURLException {
        return getDomainName(new URL(url));
    }


    public static void main(String[] args) throws UnsupportedEncodingException, MalformedURLException {
        String url = "http://www.www.wwq.weqasdsa~s-uixinba.xxqewq";
        String prefix = getDomainName(url);
        System.out.println(prefix);
    }
}
